<template>
  <div class="bigbox">
    <div class="common-header">
      <div style="cursor: pointer" @click="goback()">
        <i class="vxe-icon-arrow-left" style="vertical-align: middle"></i
        ><span style="vertical-align: middle">返回</span>
      </div>
      <div>
        <el-button type="primary" size="small" @click="exportDataEvent">导出</el-button>
      </div>
    </div>
    <div class="content_box">
      <el-scrollbar style="height: 100%">
        <div>
          <div class="info">
            <p class="title"><span class="titleName">基础信息</span></p>
            <vxe-form class="content" :data="form" @submit="searchEvent">
              <vxe-form-item title="项目编号" field="projectCode" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input
                    v-model="data.projectCode"
                    class="normal"
                    disabled
                    placeholder="项目编号"
                    clearable
                  ></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="项目全称" field="projectName" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input
                    v-model="data.projectName"
                    class="normal"
                    placeholder="请输入项目全称"
                    suffix-icon="vxe-icon-menu"
                    readonly
                    disabled
                  ></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="月份" field="month" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input
                    v-model="data.month"
                    placeholder="月份"
                    class="date"
                    type="month"
                    disabled
                    valueFormat="yyyy-MM"
                    @change="getExport"
                  ></vxe-input>
                </template>
              </vxe-form-item>
            </vxe-form>
          </div>
          <div class="info">
            <p class="title"><span class="titleName">低成本清单晾晒表</span></p>
            <div class="content">
              <vxe-table
                ref="table"
                resizable
                show-header-overflow
                align="center"
                :data="tableData"
                border
                :merge-cells="mergeCells"
              >
                <vxe-column type="seq" title="序号" width="60" show-overflow></vxe-column>
                <vxe-column field="airDryingSubcategory" title="晾晒子目" width="120" show-overflow></vxe-column>
                <vxe-column field="evaluationMode" title="考核晾晒方式" show-overflow></vxe-column>
                <vxe-column field="assessmentInstructions" title="考核晾晒说明" show-overflow></vxe-column>
                <vxe-column field="computationalFormula" title="计算公式" show-overflow></vxe-column>
                <vxe-column field="unit" title="单位" width="80" show-overflow></vxe-column>
                <vxe-column field="dept" title="牵头责任部门">
                  <template #default="{ row }">
                    <div class="deptBox">
                      <p v-for="name in row.dept ? row.dept.split(',') : []" :key="name" class="label">
                        {{ name }}
                      </p>
                    </div>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <!-- 选择项目 -->
    <!-- <Project
      ref="table"
      :dialogVisible="ProjectVisible"
      :tableData="ProjectData"
      :showSelection="true"
      :maxHeight="400"
      showPage
      :total="Projectotal"
      :pageSize="ProjectParams.size"
      :currentPage="ProjectParams.page"
      :tableColumn="tableColumn"
      @changePage="changePage"
      @sizeChange="sizeChange"
      @refresh="refreshPro"
      @searchPro="searchProject"
      @changeSelection="handleSelect"
      @rowClick="rowClick"
      @submit="submitProject3"
      @hideDialog="closeProject3"
    ></Project> -->
  </div>
</template>
<script>
import * as ExcelJS from 'exceljs';
import VXETable from 'vxe-table';
import util from '@/util/util';
export default {
  data() {
    return {
      form: {
        projectId: '',
        projectCode: '',
        projectName: '',
        month: '',
      },
      statuss: [
        { label: '禁用', value: '0' },
        { label: '启用', value: '1' },
      ],
      result: {
        code: 0,
        message: '操作成功',
        data: [
          {
            id: '1659100376131543042',
            parentId: null,
            airDryingSubcategory: '钢筋',
            evaluationMode: null,
            assessmentInstructions: null,
            computationalFormula: null,
            unit: null,
            dept: null,
            operationField: null,
            lineNumber: null,
            enabledFlag: true,
            remark: '',
            children: [
              {
                id: '1659100842152271874',
                parentId: '1659100376131543042',
                airDryingSubcategory: null,
                evaluationMode: '钢筋废料率',
                assessmentInstructions: '废钢筋处理量/钢筋耗用量1',
                computationalFormula: '1',
                unit: '万元',
                dept: '工程管理部',
                operationField: '累计产值1',
                lineNumber: null,
                enabledFlag: true,
                remark: '',
                children: null,
              },
              {
                id: '1659101996638642177',
                parentId: '1659100376131543042',
                airDryingSubcategory: '',
                evaluationMode: '钢筋库存率',
                assessmentInstructions: '月初库存/本月耗用',
                computationalFormula: '6',
                unit: '万元',
                dept: '工程管理部',
                operationField: '地产-1',
                lineNumber: null,
                enabledFlag: true,
                remark: '',
                children: null,
              },
              {
                id: '1659102004389715970',
                parentId: '1659100376131543042',
                airDryingSubcategory: '',
                evaluationMode: '钢筋库存率',
                assessmentInstructions: '月初库存/本月耗用',
                computationalFormula: null,
                unit: '万元',
                dept: '工程管理部',
                operationField: '开累产值',
                lineNumber: null,
                enabledFlag: true,
                remark: '',
                children: null,
              },
              {
                id: '1659104421160263681',
                parentId: '1659100376131543042',
                airDryingSubcategory: '',
                evaluationMode: '钢筋库存率',
                assessmentInstructions: '月初库存/本月耗用',
                computationalFormula: null,
                unit: '万元',
                dept: '工程管理部',
                operationField: '开累产值',
                lineNumber: null,
                enabledFlag: true,
                remark: '',
                children: null,
              },
              {
                id: '1659104532590338050',
                parentId: '1659100376131543042',
                airDryingSubcategory: '',
                evaluationMode: '钢筋库存率',
                assessmentInstructions: '月初库存/本月耗用',
                computationalFormula: null,
                unit: '万元',
                dept: '工程管理部',
                operationField: '开累产值',
                lineNumber: null,
                enabledFlag: true,
                remark: '',
                children: null,
              },
            ],
          },
        ],
        detailMessage: '',
        throwableClass: null,
        success: true,
      },
      tableData: [],
      newTable: [],
      tableImport: {
        // 自定义类型
        types: ['xlsx'],
      },
      tableExport: {
        // 默认选中类型
        type: 'xlsx',
        // 自定义类型
        types: ['xlsx', 'csv', 'html', 'xml', 'txt'],
      },
      fileList: [],
      atozStr: 'ABCDEFGHI',
      atozArr: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
      column: 4,
      selections: [],
      selection: {},
      projectId: 102,
      month: '2023-05',
      mergeCells: [],
      tableColumn: {
        projectCode: {
          label: '项目编码',
        },
        projectName: {
          label: '项目名称',
        },
        orgName: {
          label: '所属组织',
        },
      },
      ProjectData: [],
      //项目请求
      ProjectParams: {
        code: null,
        name: null,
        order: null,
        orderField: null,
        page: 1,
        size: 10,
      },
      ProjectVisible: false,
      Projectotal: null,
    };
  },
  filters: {
    formatStatus(val) {
      const statuss = ['禁用', '启用'];
      return statuss[val];
    },
    formatterDept(value) {
      if (!value) {
        return '';
      }
      return value.split(',');
    },
  },
  async created() {
    // 获取url参数
    this.getQuery();
    // 数据
    //     this.tableData = this.result.data;
    await this.getExport();
    // this.getProjectList();
  },
  methods: {
    parseTime: util.parseTime,
    async getExport() {
      const { projectCode: projectId, month } = this.form;
      await this.$api.ApiLowcostTemplateExport({ projectId, month }).then((res) => {
        try {
          function flatten(arr = []) {
            return arr.reduce(function (prev, item) {
              if (!item.children || item.children.length === 0) {
                return prev.concat({
                  ...item,
                });
              } else {
                return prev.concat(
                  flatten(
                    item.children.map((it) => {
                      return {
                        ...it,
                        airDryingSubcategory: item.airDryingSubcategory,
                        dept: item.dept,
                      };
                    }) || [],
                  ),
                );
              }
            }, []);
          }
          this.tableData = this.tranform(flatten(res.data));
        } catch {}
      });
    },

    goback() {
      jDiwork.closeWin();
      jDiwork.openService('1743701729433092101');
    },
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      if (!query) {
        query = window.location.hash.split('?')[1];
      }
      if (!query) {
        return;
      }
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) {
          return decodeURIComponent(pair[1]);
        }
      }
      return '';
    },
    getQuery() {
      this.form.projectId = this.getQueryVariable('id');
      this.form.projectCode = this.getQueryVariable('projectCode');
      this.form.projectName = this.getQueryVariable('projectName');
      this.form.month = this.getQueryVariable('month');
    },
    activeCellMethod(item) {
      const { row, column } = item;
      const { _X_ROW_KEY, ...rest } = row;
      const keys = Object.keys(rest);
      const len = keys.length;
      return len % 2 === 0
        ? keys.indexOf(column.field) % 2 !== 0
        : column.field !== 'A' && keys.indexOf(column.field) % 2 === 0;
    },
    //选择项目的操作
    openProject() {
      this.ProjectVisible = true;
    },
    closeProject3() {
      this.ProjectVisible = false;
    },
    //获取项目
    getProjectList() {
      this.$api.ApiProjectPlanLedgerProjectPageListFetch(this.ProjectParams).then((res) => {
        this.ProjectData = res.data.list;
        this.Projectotal = res.data.total;
      });
    },
    refreshPro() {
      this.ProjectParams.page = 1;
      this.ProjectParams.name = null;
      this.ProjectParams.code = null;
      this.getProjectList();
    },
    changePage(val) {
      this.ProjectParams.page = val;
      this.getProjectList();
    },
    rowClick(row) {
      row.flag = !row.flag;
      this.$refs['table'].$refs['table'].$refs['table'].toggleRowSelection(row, row.flag);
    },
    submitProject3() {
      if (this.pojectjectList.length == 0) return this.$message.error('请选择项目');
      this.ProjectVisible = false;
      if (this.pojectjectList.length > 0 && this.pojectjectList[0] != undefined) {
        this.form.projectCode = this.pojectjectList[0].projectCode;
        this.form.projectName = this.pojectjectList[0].projectName;
      } else {
        this.form.projectCode = '';
        this.form.projectName = '';
      }
    },
    sizeChange(val) {
      this.ProjectParams.size = val;
      this.getProjectList();
    },
    searchProject(vname, vcode) {
      this.ProjectParams.name = vname;
      this.ProjectParams.code = vcode;
      this.ProjectParams.page = 1;
      this.getProjectList();
    },
    handleSelect(e) {
      if (e.length > 1) {
        this.$refs['table'].$refs['table'].$refs['table'].clearSelection();
        this.$refs['table'].$refs['table'].$refs['table'].toggleRowSelection(e.pop());
      } else {
        if (e.length == 1) {
          this.jectjectList = [e.pop()];
        } else {
          this.jectjectList = [];
        }
      }
    },
    searchEvent() {},
    save() {
      this.$api.ApiOperationalInfoImport(this.tableData).then((res) => {});
    },
    handleRemove() {},
    tranform(table) {
      const transformRow = (list, column = 1, row = 0) => {
        let start = 0;
        while (start < list.length) {
          const first = list[start];
          const last = list.lastIndexOf(first);
          if (start !== last) {
            this.mergeCells.push({
              row: start + row,
              col: column,
              rowspan: last - start + 1,
              colspan: 1,
            });
          }
          start = last + 1;
        }
      };
      const airDryingSubcategorys = table.flat(1).map((item) => item.airDryingSubcategory);
      transformRow(airDryingSubcategorys, 1);
      let prevParentId = null;
      const prev = table.flat(1).reduce((prev, cur) => {
        if (prevParentId !== cur.parentId) {
          prevParentId = cur.parentId;
          prev.push([cur]);
        } else {
          prev[prev.length - 1].push(cur);
        }
        return prev;
      }, []);
      let i = 0;
      prev.forEach((list) => {
        const depts = list.map((item) => item.dept);
        transformRow(depts, 6, i);
        i += depts.length;
      });
      return table.flat(1);
    },
    exportDataEvent() {
      const fixedRow = 1;
      this.$refs.table.exportData({
        filename: '低成本晾晒表',
        sheetName: '低成本晾晒表',
        type: 'xlsx',
        useStyle: true,
        columnFilterMethod: (column, $columnIndex) => {
          return !(column.$columnIndex === 0);
        },
        sheetMethod: ({ options, workbook, worksheet }) => {
          // 插入标题
          worksheet.insertRow(1, ['低成本晾晒表']);
          worksheet.mergeCells(1, 1, 1, 6);
          const fixedIndex = 1;
          //  typeof row.dept === 'string' ? row.dept.replaceAll(',', '\r\n') : row.dept
          this.mergeCells.forEach((mergeCell) => {
            const { row, col, rowspan, colspan } = mergeCell;
            worksheet.mergeCells(
              row + fixedRow + fixedIndex + 1,
              col,
              row + rowspan + fixedIndex + 1,
              col + colspan - 1,
            );
          });
          // 设置所有单元格
          worksheet.eachRow((row) => {
            row._cells.forEach((item) => {
              item.value = typeof item.value === 'string' ? item.value.replaceAll('\n\n', '\r\n') : item.value;
              item.border = {
                top: { style: 'thin', color: { argb: '000000' } },
                left: { style: 'thin', color: { argb: '000000' } },
                bottom: { style: 'thin', color: { argb: '000000' } },
                right: { style: 'thin', color: { argb: '000000' } },
              };
            });
            row.eachCell((cell) => {
              //设置单元格样式
              cell.fill = {
                type: 'pattern',
                pattern: 'thin',
                fgColor: { argb: 'FF000000' },
              };
              cell.font = { color: { argb: 'FF000000' } };
              // 设置自动换行
              cell.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center' };
            });
          });
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-button--primary {
    background-color: #165dff !important;
  }
  .vxe-form--item-title .vxe-form--item-title-label {
    width: 56px;
    height: 22px;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
    line-height: 22px;
  }
  .vxe-form--item .vxe-form--item-inner .vxe-form--item-content {
    width: 370px;
    height: 32px;
  }
  .vxe-input {
    width: 100%;
  }
  .vxe-input--inner[disabled] {
    background: #f2f3f5;
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
  }
  .normal {
    width: 370px;
  }
  .date {
    width: 164px;
    border-radius: 2px 2px 2px 2px;
  }
  .download {
    width: 110px;
    height: 32px;
    background: #f2f3f5;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
  }
  .upload {
    width: 110px;
    height: 32px;
    background: #165dff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    color: #fff;
  }
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .row--level-1 {
    background-color: #f7f7f770;
  }
}
.content_box {
  height: calc(100% - 60px);
  padding: 15px 24px;
  background-color: #fff;
  margin-top: 62px;
}
</style>
